%% This Function will resample TRC files to a different data collection
%% rate.  It expects an optional input to be the path to a valid TRC file.  If no
%% argument is passed, it will ask the user to select a file using a dialog
%% box.  It will save the resulting TRC file in a new folder (called
%% Resample), with the same filename.
function resampleTRC(varargin);

% TODO: need to allow user to select input and output data rate
inrate = 60;
outrate = 240;

if nargin < 1
    % user did not specify an path, give a dialog to do so
    % this will store the last path name in the main app data structure
    lastPath = getappdata(0, 'lastPath');
    if isempty(lastPath); lastPath = 'C:\'; end;
    [name, pathstr] = uigetfile('*.trc', 'Pick a *.trc file to resample', lastPath);
    if name == 0; return; end;
    setappdata(0, 'lastPath', pathstr);
    trcpath = fullfile(pathstr,name);
elseif nargin == 1
    % user specified a path to an mha file
    % break down input file name
    trcpath = varargin{1};
    [pathstr, name, ext, versn] = fileparts(trcpath);
elseif nargin > 1
    % i do not know what to do with this many parameters
%     disp('ERROR: This function expects 0 or 1 arguments.')
%     return
    % For now i will run in script mode if more than 1 argument is passed
    pathstr = '\\Motionlab1-dell\motionlabshare\Sports Performance\Baseball\MLB_Study\1275\Processed\15Markers';
    name = '1275jl13.trc';
    trcpath = fullfile(pathstr,name);
end

[frames MkrData mkrName rate Header] = MkrDataRead2(trcpath);
for i = 1:3
    resampleData(:,:,i) = resample(inrate, outrate, MkrData(:,:,i));
end

for i = 1:length(mkrName)
    for j = 1:3
        saveData(:,(i-1)*3+j) = resampleData(:,i,j);
    end
end

saveName = fullfile(pathstr,'Resampled',name);

if exist(saveName)
    disp([saveName ' >> already exist! Nothing was saved.'])
    reply = input('Do you want to delete this file? Y/N [N]: ', 's');
    if isempty(reply)
        reply = 'N';
        disp('Exiting...')
        return;
    elseif reply == 'Y'
        disp('Deleting file...')
        delete(saveName);
    else
        disp('I did not understand your input, i am giving up...')
        return;
    end
end

if ~exist([pathstr,'\Resampled']); mkdir(pathstr,'Resampled'); end;

writetrc(saveName,saveData,Header,outrate,length(saveData),length(mkrName),inrate);

disp('Finished!');

